﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Reflection.PortableExecutable;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace ZiChen.SoXunLeiPan.Service
{
    public class HttpService(IHttpClientFactory httpClientFactory) : IHttpService
    {
        private readonly IHttpClientFactory _httpClientFactory = httpClientFactory;

        private static readonly JsonSerializerOptions _jsonSerializerOptions = new JsonSerializerOptions
        {
            WriteIndented = false,
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
            Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
        };

        /// <summary>
        /// 发送 GET 请求并反序列化为指定类型
        /// </summary>
        public async Task<T> GetAsync<T>(string url, string clientName = "default",IDictionary<string, string>? headers = null)
        {
            var client = _httpClientFactory.CreateClient(clientName);
            using var response = await client.GetAsync(url);
            if (response.IsSuccessStatusCode)
            {
                var content = await response.Content.ReadAsStreamAsync();
                var result = await JsonSerializer.DeserializeAsync<T>(content, _jsonSerializerOptions).ConfigureAwait(false);
                return result;
            }
            return default;
        }

        /// <summary>
        /// 发送 POST 请求并发送 JSON 数据
        /// </summary>
        public async Task<TResponse> PostAsync<TRequest, TResponse>(string url, TRequest data, string clientName = "default", IDictionary<string, string>? headers = null)
        {
            using var client = _httpClientFactory.CreateClient(clientName);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            AddCustomHeaders(client, headers);
            var json = JsonSerializer.Serialize(data, _jsonSerializerOptions);
            var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
            try
            {
                using var response = await client.PostAsync(url, content);
                if (response.IsSuccessStatusCode)
                {
                    var asa = await response.Content.ReadAsStringAsync();
                    var responseStream = await response.Content.ReadFromJsonAsync<TResponse>();

                    return responseStream;
                }
                return default;
            }
            catch
            {
                return default;
            }
        }
        private void AddCustomHeaders(HttpClient client, IDictionary<string, string>? headers)
        {
            if (headers == null || !headers.Any())
                return; 

            foreach (var (key, value) in headers)
            {
                if (!client.DefaultRequestHeaders.Contains(key))
                {
                    client.DefaultRequestHeaders.TryAddWithoutValidation(key, value);
                }
            }
        }

    }
}
